//
//  ICMyRedPacketViewController.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/8.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICMyRedPacketViewController.h"
#import "ICMyRedPacketHeaderView.h"
#import "ICMyRedPacketTableViewCell.h"
#import "ICRedPacketSingleViewController.h"
#import "ICRedPacketGroupViewController.h"
#import "ICRedPacketResultViewController.h"
#import "ICRedPacketReceiveView.h"
#import "ICRedPacketPayPasswordView.h"
#import "ICMyHistoryListModel.h"
#import "ICHistoryListModel.h"
#import "ICRedPacketNetworkManager.h"
#import "ICHeaderFile.h"

#define DatePickerHeight 150
#define ToolBarHeight 40

@interface ICMyRedPacketViewController () <UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource, ICMyRedPacketHeaderViewDelegate>
@property (nonatomic, strong) ICMyRedPacketHeaderView *headerView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UIPickerView *datePicker;
@property (nonatomic, strong) UIView *toolBarView;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *doneButton;
@property (nonatomic, strong) NSMutableArray *pickerArray;
@property (nonatomic, assign) NSInteger currDateRow;
@property (nonatomic, assign) NSString *currYear;
@property (nonatomic, strong) NSMutableArray *dataList;
@end

@implementation ICMyRedPacketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUI];
    [self initFooterRefresh];
    [self setNav];
    [self getData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavBackgroundColor:NE_REDPACKET_BACKGROUND_COLOR];
    [self setNavShadowColor:NE_REDPACKET_BACKGROUND_COLOR];
}

#pragma mark - private methods

// 设置页面布局
- (void)setUI {
    CGRect rect = self.headerView.frame;
    rect.size.height = App_Frame_Width / 375.0 * rect.size.height;
    self.headerView.frame = rect;
    [self.headerView addBottomBorderWithColor:LINEBACKGROUNDCOLOR andWidth:0.5];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    WEAKSELF;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf removeCoverView];
    }];
    [self.coverView addGestureRecognizer:tap];
}
- (void)initFooterRefresh {
    WEAKSELF;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf fetchMoreData];
    }];
}
// 设置navigation
- (void)setNav {
    self.title = @"新奥红包";
    
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamedFromiComeSDKBundle:@"App_back_white"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)]];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_modify_password"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)]];
}
// 网络请求
- (void)getData {
    self.currYear = [NSString stringWithFormat:@"%ld", [[NSDate date] year]];
    self.pickerArray = [self getAllYearArray];
    [self.dataList removeAllObjects];
    
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"yyyy":_currYear,
                            @"id":@0,
                            @"pageSize":@20};
    WEAKSELF
    [MBProgressHUD showLoadingActivityView:self.view];
    [self getMyHistoryListWithParam:param callback:^{
        [weakSelf.tableView.mj_footer endRefreshing];
       // [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

- (void)fetchMoreData {
    ICHistoryListModel *model = [self.dataList lastObject];
    NSString *snId = model.snId == nil ? @"0" : model.snId;
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"yyyy":_currYear,
                            @"id":[NSNumber numberWithString:snId],
                            @"pageSize":@20};
    WEAKSELF
    [self getMyHistoryListWithParam:param callback:^{
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)getMyHistoryListWithParam:(NSDictionary *)param
                         callback:(void (^)())callback {
    WEAKSELF
    // 我的红包流水
    [[ICRedPacketNetworkManager sharedInstance] myHistoryListWithParam:param success:^(id object) {
        callback();
        ICMyHistoryListModel *model = [ICMyHistoryListModel mj_objectWithKeyValues:[object objectForKey:@"data"]];
        for (ICHistoryListModel *item in model.list) {
            [weakSelf.dataList addObject:item];
        }
        weakSelf.headerView.model = model;
        [weakSelf.tableView reloadData];
    } failure:^(NSError *error) {
        callback();
        [MBProgressHUD showError:error.domain];
    }];
}

- (NSMutableArray *)getAllYearArray {
    int currYear = (int)[[NSDate date] year];
    NSMutableArray *tempArry = [[NSMutableArray alloc] init];
    for (int i = currYear; i >= 2016; i--) {
        [tempArry addObject:[NSString stringWithFormat:@"%d", i]];
    }
    return tempArry;
}

- (void)datePickerHidden {
    [UIView animateWithDuration:0.3 animations:^{
        self.datePicker.y = App_RootCtr.view.height + ToolBarHeight;
        self.toolBarView.bottom = self.datePicker.top;
    }];
}

- (void)removeCoverView {
    [self.coverView removeFromSuperview];
    [self datePickerHidden];
}

#pragma mark - event response

- (void)leftButtonAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonAction:(id)sender {
    
    
    UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketPasswordViewController:nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)cancelBtnClicked:(id)sender {
    [self removeCoverView];
}

- (void)doneBtnClicked:(id)sender {
    self.currYear = self.pickerArray[_currDateRow];
    [self.headerView.yearButton setTitle:[NSString stringWithFormat:@"%@年", _currYear] forState:UIControlStateNormal];
    [self removeCoverView];
    [self.dataList removeAllObjects];

    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"yyyy":_currYear,
                            @"id":@0,
                            @"pageSize":@20};
    WEAKSELF
    [MBProgressHUD showLoadingActivityView:self.view];
    [self getMyHistoryListWithParam:param callback:^{
        [weakSelf.tableView.mj_footer endRefreshing];
        //[MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

#pragma mark - ICMyRedPacketHeaderViewDelegate

- (void)dateBtnClicked {
    [App_RootCtr.view addSubview:self.coverView];
    self.coverView.frame = App_RootCtr.view.bounds;
    [UIView animateWithDuration:0.3 animations:^{
        self.datePicker.y = App_RootCtr.view.height - DatePickerHeight;
        self.toolBarView.bottom = self.datePicker.top;
        self.coverView.bottom = self.toolBarView.top;
    }];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //往下拉图片放大
    CGFloat y = scrollView.contentOffset.y;
    CGRect frame = self.headerView.stretchImageView.frame;
    frame.origin.y = y;
    frame.size.height = -y;
    self.headerView.stretchImageView.frame = frame;
}

#pragma mark - Picker Datasource

//列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

//列显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.pickerArray count];
}

#pragma mark - Picker Delegate

//当前行的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return self.pickerArray[row];
}

//点击当前行的内容
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.currDateRow = row;
}

//修改Label字体大小
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.width, 20)];
    label.text = [self.pickerArray objectAtIndex:row];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:15];
    return label;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataList count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [ICMyRedPacketTableViewCell cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"MyRedPacketCell";
    ICMyRedPacketTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[ICMyRedPacketTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.model = self.dataList[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Getter

- (ICMyRedPacketHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ICMyRedPacketHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 150)];
        _headerView.delegate = self;
    }
    return _headerView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.userInteractionEnabled = YES;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
        _tableView.tableHeaderView = self.headerView;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectZero];
        _coverView.backgroundColor = [UIColor blackColor];
        _coverView.alpha = 0.5;
    }
    return _coverView;
}

- (UIPickerView *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, App_RootCtr.view.height + ToolBarHeight, App_RootCtr.view.width, DatePickerHeight)];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.delegate = self;
        _datePicker.dataSource = self;
        [App_RootCtr.view addSubview:_datePicker];
    }
    return _datePicker;
}

- (UIView *)toolBarView {
    if (!_toolBarView) {
        _toolBarView = [[UIView alloc] initWithFrame:CGRectMake(0, App_RootCtr.view.height, App_RootCtr.view.width, ToolBarHeight)];
        _toolBarView.backgroundColor = [UIColor whiteColor];
        [App_RootCtr.view addSubview:_toolBarView];
        [_toolBarView addSubview:self.cancelButton];
        [_toolBarView addSubview:self.doneButton];
        [_toolBarView addTopBorderWithColor:LINEBACKGROUNDCOLOR andWidth:0.5];
    }
    return _toolBarView;
}

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, (ToolBarHeight+10)*Level, ToolBarHeight*Level)];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:ICRGB(0x89c44d) forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)doneButton {
    if (!_doneButton) {
        _doneButton = [[UIButton alloc] initWithFrame:CGRectMake(self.datePicker.width-ToolBarHeight*Level-10, 0, ToolBarHeight+10, ToolBarHeight*Level)];
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_doneButton setTitle:@"完成" forState:UIControlStateNormal];
        [_doneButton setTitleColor:ICRGB(0x89c44d) forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(doneBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneButton;
}

- (NSMutableArray *)pickerArray {
    if (!_pickerArray) {
        _pickerArray = [NSMutableArray array];
    }
    return _pickerArray;
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

@end
